package com.taijihuabao.modules.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.taijihuabao.common.commonutils.BusinessIdUtil;
import com.taijihuabao.common.commonutils.PageResult;
import com.taijihuabao.common.emailutils.EmailPojo;
import com.taijihuabao.common.rabbitmq.RabbitMqProducer;
import com.taijihuabao.common.redisconfig.UserLoad;
import com.taijihuabao.modules.entity.*;
import com.taijihuabao.modules.enums.optenums.approval.ApprovalStatusEnum;
import com.taijihuabao.modules.enums.optenums.approval.BusinessEnum;
import com.taijihuabao.modules.mapper.*;
import com.taijihuabao.modules.model.approval.vo.ApplyVO;
import com.taijihuabao.modules.model.approval.dto.ApprovalProcessDTO;
import com.taijihuabao.modules.model.approval.vo.ApprovalVO;
import com.taijihuabao.modules.enums.optenums.dept.DeptEnum;
import com.taijihuabao.modules.model.approval.dto.ApproveCompleteDTO;
import com.taijihuabao.modules.model.user.vo.UserInfoVO;
import com.taijihuabao.modules.service.ApprovalProcessService;
import org.activiti.engine.*;
import org.activiti.engine.task.Task;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 审批流程
 *
 * @Author Xiao
 */
@Service
public class LeaveApprovalServiceImpl implements ApprovalProcessService {

    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private ApprovalHistoryMapper approvalHistoryMapper;
    @Resource
    private ApprovalBusinessMapper approvalBusinessMapper;
    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private DeptMapper deptMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Resource
    private RabbitMqProducer rabbitMqProducer;
    @Resource
    private UserMapper userMapper;
    @Resource
    private LeaveBusinessMapper leaveBusinessMapper;
    @Resource
    private LeaveBusinessHistoryMapper leaveBusinessHistoryMapper;

    /**
     * 本部门审批节点
     */
    private final String DEPT_FLOW = "本部门审批";
    /**
     * 父部门审批节点
     */
    private final String PARENT_DEPT_FLOW = "父部门审批";
    /**
     * 人事部审批节点
     */
    private final String PERSONNEL_DEPT_FLOW = "人事部审批";

    /**
     * 部署请假流程
     */
    @Override
    public void deploy() {
        //部署流程定义并获取流程部署对象
        repositoryService
                .createDeployment()
                .name("请假审批")
                .addClasspathResource("bpmn/leaveApproval.bpmn")
                .deploy();
    }

    /**
     * 查询申请人的所有审批单
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageResult<T> selectByApplyUserId(int page, int size) {
        PageHelper.startPage(page, size);
        UserEntity userEntity = UserLoad.getUser();
        List<ApprovalVO> approvalVOList = approvalMapper.selectByApplyUserId(userEntity.getId());
        //建立新集合添加请假审批单
        List<ApprovalVO> newApprovalList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(approvalVOList)) {
            for (ApprovalVO approvalVO : approvalVOList) {
                //筛选请假审批单
                if (approvalVO.getApprovalCode().contains(BusinessEnum.LEAVE.getCode())) {
                    LeaveBusinessEntity leaveBusinessEntity = leaveBusinessMapper.selectOne(approvalVO.getApprovalCode());
                    if (!Objects.isNull(leaveBusinessEntity)) {
                        approvalVO.setStartTime(leaveBusinessEntity.getStartTime());
                        approvalVO.setEndTime(leaveBusinessEntity.getEndTime());
                        approvalVO.setDuration(leaveBusinessEntity.getDuration());
                        approvalVO.setApplyProve(leaveBusinessEntity.getApplyProve());
                        newApprovalList.add(approvalVO);
                    }
                }
            }
        }
        return new PageResult(newApprovalList);
    }

    /**
     * 根据审批编码查询审批单结果
     *
     * @param approvalCode
     * @return
     */
    @Override
    public ApprovalVO selectByApprovalCode(String approvalCode) {
        ApprovalVO approval = approvalMapper.selectByApprovalCode(approvalCode);
        if(!Objects.isNull(approval)){
            LeaveBusinessEntity leaveBusinessEntity = leaveBusinessMapper.selectOne(approvalCode);
            if(!Objects.isNull(leaveBusinessEntity)){
                approval.setStartTime(leaveBusinessEntity.getStartTime());
                approval.setEndTime(leaveBusinessEntity.getEndTime());
                approval.setDuration(leaveBusinessEntity.getDuration());
                approval.setApplyProve(leaveBusinessEntity.getApplyProve());
            }
        }
        return approval;
    }

    /**
     * 启动请假流程
     *
     * @param approvalProcessDTO
     */
    @Override
    public String startProcess(ApprovalProcessDTO approvalProcessDTO) {
        //将前台接受的json字符串转化成自己想要的实体
        LeavesEntity leavesEntity =
                JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), LeavesEntity.class);
        //拿到上传文件的url
        leavesEntity.setProveUrl(approvalProcessDTO.getFileUrl());
        //登录id
        UserEntity user = UserLoad.getUser();
        Long userId = user.getId();
        //拿到用户的部门信息
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        //拿到用户部门编码
        String deptCode = deptUserEntities.get(0).getDeptCode();
        //请假业务对象
        LeaveBusinessEntity leaveBusinessEntity = new LeaveBusinessEntity();
        //获取业务主键
        String businessId = BusinessIdUtil.createBusinessId(approvalProcessDTO.getProcessName());
        leaveBusinessEntity.setBusinessId(businessId);
        leaveBusinessEntity.setStartTime(leavesEntity.getLeavesStart());
        leaveBusinessEntity.setEndTime(leavesEntity.getLeavesEnd());
        leaveBusinessEntity.setDuration(leavesEntity.getLeavesDays());
        leaveBusinessEntity.setApplyProve(approvalProcessDTO.getFileUrl());
        leaveBusinessEntity.setApplyRemarks(leavesEntity.getLeavesRemarks());
        //新增请假业务
        leaveBusinessMapper.insertLeaveBusiness(leaveBusinessEntity);
        //业务表对象
        ApprovalBusinessEntity approvalBusinessEntity = new ApprovalBusinessEntity();
        //业务主键创建
        approvalBusinessEntity.setBusinessId(businessId);
        approvalBusinessEntity.setApplyCode(leaveBusinessEntity.getBusinessId());
        approvalBusinessEntity.setApplyContent(leavesEntity.getLeavesReason());
        approvalBusinessEntity.setApplyType(leavesEntity.getLeavesType());
        approvalBusinessEntity.setApplyRemarks(leavesEntity.getLeavesRemarks());
        //新增业务信息
        approvalBusinessMapper.insertApprovalBusiness(approvalBusinessEntity);
        //请假业务历史信息
        leaveBusinessEntity.setApplyCode(approvalBusinessEntity.getApplyCode());
        leaveBusinessEntity.setApplyContent(approvalBusinessEntity.getApplyContent());
        leaveBusinessEntity.setApplyType(approvalBusinessEntity.getApplyType());
        //新增历史信息
        leaveBusinessHistoryMapper.insertLeaveBusiness(leaveBusinessEntity);
        //审批表信息
        ApprovalEntity approvalEntity = new ApprovalEntity();
        approvalEntity.setApprovalCode(String.valueOf(approvalBusinessEntity.getBusinessId()));
        approvalEntity.setApprovalType(approvalBusinessEntity.getApplyType());
        approvalEntity.setApplyUserId(userId);
        //获取姓名
        UserInfoVO userInfoVO = userMapper.selectById(userId);
        approvalEntity.setApplyName(userInfoVO.getName());
        approvalEntity.setApplyDeptCode(deptCode);
        //新增审批
        approvalMapper.insertApproval(approvalEntity);
        //根据业务id多表查询审批信息和业务信息
        ApprovalVO approvalVO = approvalMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
        //启动请假流程
        runtimeService.startProcessInstanceByKey(approvalProcessDTO.getProcessName(),
                String.valueOf(approvalVO.getId()));
        //修改状态
        approvalMapper.updateApprovalIng(approvalEntity.getId());
        //查询任务
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(approvalProcessDTO.getProcessName())
                .processInstanceBusinessKey(String.valueOf(approvalVO.getId()))
                .taskAssignee(String.valueOf(userId)).list();
        //历史审批表
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalCode(String.valueOf(approvalBusinessEntity.getBusinessId()));
        approvalHistoryEntity.setApprovalType(approvalBusinessEntity.getApplyType());
        approvalHistoryEntity.setApplyUserId(userId);
        approvalHistoryEntity.setApplyName(userInfoVO.getName());
        approvalHistoryEntity.setApplyDeptCode(deptCode);
        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        approvalHistoryEntity.setApprovalTask(tasks.get(0).getId());
        approvalHistoryEntity.setApprovalUserId(userId);
        approvalHistoryEntity.setApprovalDeptCode(deptCode);
        //拾取任务
        taskService.claim(tasks.get(0).getId(), String.valueOf(userId));
        //流程变量集合
        Map<String, Object> map = new HashMap<>(16);
        //拾取任务
        taskService.claim(tasks.get(0).getId(), String.valueOf(userId));
        //判断申请人是否是总经理部门
        if (DeptEnum.GENERALMANAGER.getCode().equals(deptCode)) {
            //判断成员部门角色
            for (DeptUserEntity deptUser : deptUserEntities) {
                String deptRole = deptUser.getDeptRole();
                if (DeptEnum.ADMINISTRATOR.getCode().equals(deptRole) ||
                        DeptEnum.ASSESSOR.getCode().equals(deptRole)) {
                    //总经理的主管、审核员跳过多级部门审批
                    map.put("flow", "personnelDept");
                    approvalHistoryEntity.setApprovalFlow("跳过多级主管");
                    break;
                }
            }
        } else if (DeptEnum.PERSONNEL_DEPT.getCode().equals(deptCode)) {
            //考勤部门跳过多级部门审批
            map.put("flow", "personnelDept");
            approvalHistoryEntity.setApprovalFlow("跳至考勤部门");
        } else {
            //自动完成第一步提交
            map.put("flow", "approval");
            approvalHistoryEntity.setApprovalFlow(tasks.get(0).getName());
        }
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        taskService.complete(tasks.get(0).getId(),map,true);
        return approvalEntity.getApprovalCode();
    }

    /**
     * 审核待办
     *
     * @param approveCompleteDTO
     */
    @Override
    public void completeTask(ApproveCompleteDTO approveCompleteDTO) {
        UserEntity user = UserLoad.getUser();
        //用户id
        Long userId = user.getId();
        //任务Id
        String taskId = approveCompleteDTO.getTaskId();
        //审批结果
        Integer agree = approveCompleteDTO.getAgree();
        //审批意见
        String opinion = approveCompleteDTO.getApprovalOpinion();
        //领取任务
        taskService.claim(taskId, String.valueOf(userId));
        //查询当前任务对象
        Task task = ProcessEngines.getDefaultProcessEngine().getTaskService()
                .createTaskQuery().taskId(taskId).singleResult();
        //获取审批单
        String businessKey = task.getBusinessKey();
        ApprovalEntity approval = approvalMapper.selectById(Long.valueOf(businessKey));
        //审批历史
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApplyDeptCode(approval.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approval.getApplyName());
        approvalHistoryEntity.setApplyUserId(approval.getApplyUserId());
        approvalHistoryEntity.setApprovalCode(approval.getApprovalCode());
        approvalHistoryEntity.setApprovalFlow(task.getName());
        approvalHistoryEntity.setApprovalType(approval.getApprovalType());
        approvalHistoryEntity.setApprovalTask(task.getId());
        approvalHistoryEntity.setApprovalUserId(userId);
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        approvalHistoryEntity.setApprovalDeptCode(deptUserEntities.get(0).getDeptCode());
        approvalHistoryEntity.setApprovalOpinion(opinion);
        Map<String, Object> map = new HashMap<>(16);
        //申请人部门
        String applyDeptCode = approval.getApplyDeptCode();
        //申请人部门信息
        DeptEntity deptEntity = deptMapper.selectDeptByCode(applyDeptCode);
        //本部门节点
        if(DEPT_FLOW.equals(task.getName())){
            if(!Objects.isNull(deptEntity)){
                //如果没有父部门则跳过父部门审批
                if (StringUtils.isEmpty(deptEntity.getParentDept())) {
                    if (1 == agree) {
                        map.put("dept", "personnelDept");
                        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
                    }
                } else {
                    //同意或拒绝进入下一个节点
                    if (1 == agree) {
                        map.put("dept", "agree");
                        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
                    }else{
                        map.put("dept", "reject");
                        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
                    }
                }
            }
        }
        //父部门节点
        if(PARENT_DEPT_FLOW.equals(task.getName())){
            //同意或拒绝进入下一个节点
            if (1 == agree) {
                map.put("parentDept", "agree");
                approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
            }else{
                map.put("parentDept", "reject");
                approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
            }
        }
        //人事节点
        if(PERSONNEL_DEPT_FLOW.equals(task.getName())){
            //同意或拒绝进入下一个节点
            if (1 == agree) {
                map.put("personnelDept", "agree");
                approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
            }else{
                map.put("personnelDept", "reject");
                approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
            }
            //判断是否结束，结束执行抄送，结束保存历史，结束修改审批单
            isEnd(approval,task,userId,opinion);
        }
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        taskService.complete(taskId,map,true);
    }

    /**
     * 判断是否结束，结束执行抄送，结束保存历史，结束修改审批单
     * @param approval
     * @param task
     */
    public void isEnd(ApprovalEntity approval,Task task,Long userId,String opinion){
        //判断是否还有人事部任务 0表示这是最后一个任务
        List<ApprovalVO> approvals = approvalHistoryMapper.selectByApprovalCode(approval.getApprovalCode());
        //查询出此单有多少个人事任务
        int personNum = 0;
        for(ApprovalVO approvalVO : approvals){
            if (!StringUtils.isEmpty(approvalVO.getApprovalDeptCode())) {
                if (DeptEnum.PERSONNEL_DEPT.getCode().equals(approvalVO.getApprovalDeptCode())
                        &&ApprovalStatusEnum.STATE_ING.getCode().equals(approvalVO.getApprovalState())){
                    personNum++;
                }
            }
        }
        //查询出此单完成了多少个任务
        int result = 0;
        List<ApprovalVO> completelyTasks = new ArrayList<>();
        for(ApprovalVO approvalVO : approvals){
            if (!StringUtils.isEmpty(approvalVO.getApprovalDeptCode())) {
                if (DeptEnum.PERSONNEL_DEPT.getCode().equals(approvalVO.getApprovalDeptCode())
                        &&!ApprovalStatusEnum.STATE_ING.getCode().equals(approvalVO.getApprovalState())){
                    result++;
                    completelyTasks.add(approvalVO);
                }
            }
        }
        if (personNum == result) {
            //完成人事部任务后修改审批单
            int resultState = 1;
            if(PERSONNEL_DEPT_FLOW.equals(task.getName())){
                //如果全部人事同意，审批单通过
                for (ApprovalVO resultVO : completelyTasks) {
                    if (!StringUtils.isEmpty(resultVO.getApprovalState())) {
                        if(ApprovalStatusEnum.STATE_REJECT.getCode().equals(resultVO.getApprovalState())){
                            resultState = 0;
                            break;
                        }
                    }
                }
                approval.setApprovalUserId(userId);
                approval.setApprovalOpinion(opinion);
                if (resultState == 1) {
                    approval.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
                    approvalMapper.updateApproval(approval);
                } else {
                    approval.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
                    approvalMapper.updateApproval(approval);
                }
            }
            //判断是否出结果，进行抄送
            if(!ApprovalStatusEnum.STATE_ING.getCode().equals(approval.getApprovalState())){
                sendEmail(approval);
            }
        }
    }

    /**
     * 查询待办
     *
     * @param processName
     * @return
     */
    @Override
    public List<ApprovalVO> findTask(String processName) {
        //通过流程名称获取流程key
        String codeByMessage = BusinessEnum.getCodeByMessage(processName);
        //用户id
        UserEntity user = UserLoad.getUser();
        Long userId = user.getId();
        //查询任务
        List<Task> candidateUsers = taskService.createTaskQuery()
                .processDefinitionKey(codeByMessage)
                .taskCandidateUser(String.valueOf(userId)).list();
        List<Task> assignees = taskService.createTaskQuery()
                .processDefinitionKey(codeByMessage)
                .taskAssignee(String.valueOf(userId)).list();
        //所有任务
        List<Task> allTask = new ArrayList<>();
        allTask.addAll(candidateUsers);
        allTask.addAll(assignees);
        //任务信息集合
        List<ApprovalVO> taskInfo = new ArrayList<>();
        if (!CollectionUtils.isEmpty(allTask)) {
            //遍历任务传给前端
            for (Task task : allTask) {
                //根据业务键查询审批结果单
                String businesskey = task.getBusinessKey();
                //审批单
                ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(businesskey));
                //判断是否为请假的审批
                if (!Objects.isNull(approvalEntity)){
                    String leaveApproval = approvalEntity.getApprovalCode().substring(0,13);
                    if(BusinessEnum.LEAVE.getCode().equals(leaveApproval)){
                        //查询完整信息返回给前端
                        ApprovalVO oneMessage = approvalMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
                        //从表详细信息
                        oneMessage.setApprovalTask(task.getId());
                        oneMessage.setApprovalFlow(task.getName());
                        LeaveBusinessEntity leaveBusinessEntity = leaveBusinessMapper.selectOne(oneMessage.getApplyCode());
                        if(!Objects.isNull(leaveBusinessEntity)){
                            ApplyVO applyVO = new ApplyVO();
                            applyVO.setApplyContent(oneMessage.getApplyContent());
                            applyVO.setApplyProve(leaveBusinessEntity.getApplyProve());
                            applyVO.setDuration(leaveBusinessEntity.getDuration());
                            applyVO.setStartTime(leaveBusinessEntity.getStartTime());
                            applyVO.setEndTime(leaveBusinessEntity.getEndTime());
                            oneMessage.setApplyVO(applyVO);
                        }
                        taskInfo.add(oneMessage);
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(taskInfo)) {
            for (ApprovalVO approvalVO : taskInfo) {
                //获取节点名称
               List<ApprovalVO> approvals = approvalHistoryMapper.selectByApprovalCode(approvalVO.getApprovalCode());
                //根据此进程已办，取出上一条同意或拒绝的理由
                if(2<approvals.size()){
                    String opinion = approvals.get(approvals.size()-2).getApprovalOpinion();
                    if(!StringUtils.isEmpty(opinion)){
                        approvalVO.setApprovalOpinion(approvals.get(approvals.size()-2).getApprovalOpinion());
                    }
                }
                String flow = "提交申请";
               for(int i=0;i<approvals.size();i++){
                    if (flow.equals(approvals.get(i).getApprovalFlow())) {
                        if (flow.equals(approvalVO.getApprovalFlow())) {
                            approvalVO.setApprovalFlow("重新提交");
                        }
                    }
                }
            }
        }
        return taskInfo;
    }

    /**
     * 查询已审批
     *
     * @param processName
     * @return
     */
    @Override
    public List<ApprovalVO> findCompleteTask(String processName) {
        //用户id
        UserEntity user = UserLoad.getUser();
        Long userId = user.getId();
        //查询完整信息返回给前端
        List<ApprovalVO> approvalHistoryEntities = approvalHistoryMapper.selectByApprovalUserId(userId);
        if (!CollectionUtils.isEmpty(approvalHistoryEntities)) {
            for (int i = 0;i<approvalHistoryEntities.size();i++) {
                String leaveApproval = approvalHistoryEntities.get(i).getApprovalCode().substring(0,13);
                if(BusinessEnum.LEAVE.getCode().equals(leaveApproval)){
                    //业务表信息
                    ApprovalBusinessEntity approvalBusinessEntity =
                            approvalBusinessMapper.selectOne(approvalHistoryEntities.get(i).getApprovalCode());
                    //从表详细信息
                    LeaveBusinessEntity leaveBusinessEntity =
                            leaveBusinessMapper.selectOne(approvalBusinessEntity.getBusinessId());
                    if(!Objects.isNull(leaveBusinessEntity)){
                        ApplyVO applyVO = new ApplyVO();
                        applyVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                        applyVO.setApplyProve(leaveBusinessEntity.getApplyProve());
                        applyVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                        applyVO.setDuration(leaveBusinessEntity.getDuration());
                        applyVO.setStartTime(leaveBusinessEntity.getStartTime());
                        applyVO.setEndTime(leaveBusinessEntity.getEndTime());
                        approvalHistoryEntities.get(i).setApplyVO(applyVO);
                    }
                }else{
                    approvalHistoryEntities.remove(approvalHistoryEntities.get(i));
                    i--;
                }
            }
        }
        return approvalHistoryEntities;
    }

    /**
     * 查询流程进度
     *
     * @param approvalCode
     * @return
     */
    @Override
    public List<ApprovalVO> findActivities(String approvalCode) {
        List<ApprovalVO> approvals = approvalHistoryMapper.selectByApprovalCode(approvalCode);
        if(!CollectionUtils.isEmpty(approvals)){
            approvals.remove(approvals.get(0));
            for(ApprovalVO approvalVO : approvals){
                ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalCode);
                LeaveBusinessEntity leaveBusinessEntity = leaveBusinessMapper.selectOne(approvalBusinessEntity.getApplyCode());
                ApplyVO applyVO = new ApplyVO();
                applyVO.setApplyContent(leaveBusinessEntity.getApplyContent());
                applyVO.setApplyProve(leaveBusinessEntity.getApplyProve());
                applyVO.setApplyRemarks(leaveBusinessEntity.getApplyRemarks());
                applyVO.setDuration(leaveBusinessEntity.getDuration());
                applyVO.setStartTime(leaveBusinessEntity.getStartTime());
                applyVO.setEndTime(leaveBusinessEntity.getEndTime());
                approvalVO.setApplyVO(applyVO);
            }
        }
        return approvals;
    }

    /**
     * 发送审批结果
     *
     * @param approvalEntity
     */
    public void sendEmail(ApprovalEntity approvalEntity) {
        //获取历史审批信息
        List<ApprovalVO> approvals = approvalHistoryMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
        List<String> users = new ArrayList<>();
        for(ApprovalVO approvalVO : approvals){
            users.add(String.valueOf(approvalVO.getApprovalUserId()));
        }
        //去重
        HashSet set = new HashSet(users);
        users.clear();
        users.addAll(set);
        //向已指定的人员发送邮件
        List<String> receivers = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            UserInfoVO userEntity = userMapper.selectById(Long.valueOf(users.get(i)));
            receivers.add(userEntity.getUserEmail());
        }
        //以邮件形式抄送
        EmailPojo emailPojo = new EmailPojo();
        if(ApprovalStatusEnum.STATE_PASS.getCode().equals(approvalEntity.getApprovalState())){
            emailPojo.setSubject(approvalEntity.getApprovalType()+"——"+"审批通过");
        }else {
            emailPojo.setSubject(approvalEntity.getApprovalType()+"——"+"审批拒绝");
        }
        //申请人
        String applyer = userMapper.selectById(approvalEntity.getApplyUserId()).getName();
        //审批人
        String approver = userMapper.selectById(approvalEntity.getApprovalUserId()).getName();
        //申请所在部门
        DeptEntity deptEntity = deptMapper.selectDeptByCode(approvalEntity.getApplyDeptCode());
        //申请内容
        String content = "申请人：" + applyer + " 部门：" + deptEntity.getDeptName() + " \n"
                //+"申请内容："+approvalEntity.getApprovalType()+"——"+approvalEntity.getApplyContent()+" \n"
                //+"备注："+approvalEntity.getApplyRemarks()+" \n"
                + "审批意见：" + approvalEntity.getApprovalOpinion() + " \n"
                + "审批人：" + approver + " \n"
                + "编码：" + approvalEntity.getApprovalCode() + " \n";
        emailPojo.setContent(content);
        emailPojo.setReceiver(receivers);
        rabbitMqProducer.commonMailProducer(emailPojo);
    }

    /**
     * 修改请假，并重新申请
     *
     * @param approvalProcessDTO
     */
    @Override
    public String reSubmit(ApprovalProcessDTO approvalProcessDTO) {
        //将前台接受的json字符串转化成自己想要的实体
        LeavesEntity leavesEntity =
                JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), LeavesEntity.class);
        //拿到上传文件的url
        UserEntity user = UserLoad.getUser();
        //登录id
        Long userId = user.getId();
        //拿到用户的部门信息
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userId);
        //拿到用户部门编码
        String deptCode = deptUserEntities.get(0).getDeptCode();
        //请假业务对象
        LeaveBusinessEntity leaveBusinessEntity = leaveBusinessMapper.selectOne(leavesEntity.getBusinessId());
        leaveBusinessEntity.setStartTime(leavesEntity.getLeavesStart());
        leaveBusinessEntity.setEndTime(leavesEntity.getLeavesEnd());
        leaveBusinessEntity.setDuration(leavesEntity.getLeavesDays());
        leaveBusinessEntity.setApplyProve(approvalProcessDTO.getFileUrl());
        leaveBusinessEntity.setApplyRemarks(leavesEntity.getLeavesRemarks());
        //修改请假业务
        leaveBusinessMapper.updateLeaveBusiness(leaveBusinessEntity);
        //业务表对象
        ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(leavesEntity.getBusinessId());
        approvalBusinessEntity.setApplyContent(leavesEntity.getLeavesReason());
        approvalBusinessEntity.setApplyType(leavesEntity.getLeavesType());
        //修改业务信息
        approvalBusinessMapper.updateApprovalBusiness(approvalBusinessEntity);
        //请假业务历史信息
        leaveBusinessEntity.setApplyCode(approvalBusinessEntity.getApplyCode());
        leaveBusinessEntity.setApplyContent(approvalBusinessEntity.getApplyContent());
        leaveBusinessEntity.setApplyType(approvalBusinessEntity.getApplyType());
        //新增历史信息
        leaveBusinessHistoryMapper.insertLeaveBusiness(leaveBusinessEntity);
        //审批表信息
        ApprovalEntity approvalEntity = approvalMapper.selectOne(approvalBusinessEntity.getBusinessId());
        approvalEntity.setApprovalType(approvalBusinessEntity.getApplyType());
        approvalEntity.setApplyUserId(userId);
        //获取姓名
        UserInfoVO userInfoVO = userMapper.selectById(userId);
        approvalEntity.setApplyName(userInfoVO.getName());
        approvalEntity.setApplyDeptCode(deptCode);
        approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_ING.getCode());
        //修改审批
        approvalMapper.updateApproval(approvalEntity);
        //根据业务id多表查询审批信息和业务信息
        ApprovalVO approvalVO = approvalMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
        //重新申请的任务对象
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(approvalProcessDTO.getProcessName())
                .taskAssignee(String.valueOf(userId)).list();
        //保存审批历史
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApplyDeptCode(approvalVO.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approvalVO.getApplyName());
        approvalHistoryEntity.setApplyUserId(approvalVO.getApplyUserId());
        approvalHistoryEntity.setApprovalCode(approvalVO.getApprovalCode());
        approvalHistoryEntity.setApprovalFlow(tasks.get(0).getName());
        approvalHistoryEntity.setApprovalOpinion(null);
        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        approvalHistoryEntity.setApprovalType(approvalVO.getApprovalType());
        approvalHistoryEntity.setApprovalTask(tasks.get(0).getId());
        //拿到用户的部门信息
        approvalHistoryEntity.setApprovalDeptCode(deptUserEntities.get(0).getDeptCode());
        approvalHistoryEntity.setApprovalUserId(userId);
        //拾取任务
        taskService.claim(tasks.get(0).getId(),String.valueOf(userId));
        //流程变量集合
        Map<String, Object> map = new HashMap<>(16);
        //拾取任务
        taskService.claim(tasks.get(0).getId(),String.valueOf(userId));
        //判断申请人是否是总经理部门
        if(DeptEnum.GENERALMANAGER.getCode().equals(deptCode)){
            //判断成员部门角色
            for(DeptUserEntity deptUser : deptUserEntities){
                String deptRole = deptUser.getDeptRole();
                if(DeptEnum.ADMINISTRATOR.getCode().equals(deptRole) ||
                        DeptEnum.ASSESSOR.getCode().equals(deptRole) ){
                    //总经理的主管、审核员跳过多级部门审批
                    map.put("flow", "personnelDept");
                    approvalHistoryEntity.setApprovalFlow("跳过多级主管");
                    break;
                }
            }
        }else if(DeptEnum.PERSONNEL_DEPT.getCode().equals(deptCode)){
            //考勤部门跳过多级部门审批
            map.put("flow", "personnelDept");
            approvalHistoryEntity.setApprovalFlow("跳至考勤部门");
        }else{
            //自动完成第一步提交
            map.put("flow","approval");
            approvalHistoryEntity.setApprovalFlow(tasks.get(0).getName());
        }
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        taskService.complete(tasks.get(0).getId(),map,true);
        return approvalEntity.getApprovalCode();
    }

    @Override
    public String getProcessName() {
        return "leaveApproval";
    }

}

